<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Exception;//事务处理

class Buypo extends Auth
{
    public function __construct(Request $request){
        parent::__construct($request);
        $this->data = $request->param();
        $this->user_id = session('userid') == null ? 1 : session('userid');
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
    }

    // 采购合同
    public function list(Request $request)
    {   
        if($request->isAjax()){
            $join = [
                        ['company c','zu.company_id = c.id','LEFT'],
                        ['port p','zu.port_id = p.id','LEFT']        // 交货地址
                    ];
            $where['zu.status'] = 1;
            if(isset($this->data['play']) && $this->data['play'] == 'true') $where['zu.paid_sum'] = ['>',0];
            if(isset($this->data['sign']) && $this->data['sign'] == 'true') $where['zu.sign_day'] = ['>',0];
            if(isset($this->data['receipt']) && $this->data['receipt'] == 'true') $where['zu.receipt_day'] = ['>',0];
            if(isset($this->data['del']) && $this->data['del'] == 'true') $where['zu.status'] = 2;
            if(isset($this->data['searchText']) && $this->data['searchText']) $where['c.name'] = ['like','%'.$this->data['searchText'].'%'];
            // dump($where);die;
            $limit = isset($this->data['page']) ? $this->data['page']*$this->data['limit'].','.$this->data['limit'] : '';
            $data = model('Buy')->getBuyPo($where,$this->lang,'','',$limit);
            if(!empty($data)){
                foreach ($data as $k => $v) {
                    $data[$k]['buy_po_pack'] = getDatas('buy_po_pack',['*'],['po_id'=>$v['id']]);
                    if(!empty($data[$k]['buy_po_pack'])){
                        foreach ($data[$k]['buy_po_pack'] as $k1 => $v1) {
                            $proList = model('Buy')->getProAndProchar($v1['pro_id'],$v1['prochar_id'],$this->lang);
                            if(!empty($proList)){
                                $data[$k]['buy_po_pack'][$k1]['pro_name'] = $proList['proList']['content'];
                                $data[$k]['buy_po_pack'][$k1]['brand_name'] = $proList['proList']['brand_name'];
                                $data[$k]['buy_po_pack'][$k1]['img_url'] = $proList['proList']['img_url'];
                                $data[$k]['buy_po_pack'][$k1]['model'] = $proList['prochar']['model'];
                                $data[$k]['buy_po_pack'][$k1]['qty_sum'] = $v1['qty']*$v1['ctn_qty'];
                                $data[$k]['buy_po_pack'][$k1]['kgs_sum'] = $v1['qty']*$v1['ctn_kgs'];
                                $data[$k]['buy_po_pack'][$k1]['m3_sum'] = $v1['qty']*$v1['ctn_m3'];
                                if($v1['container_id'] > 0){
                                    $container = $this->getContainerStatus($v1['container_id']);
                                    $data[$k]['buy_po_pack'][$k1]['name'] = $container['name'];
                                    $data[$k]['buy_po_pack'][$k1]['container_status'] = $container['status'];
                                    $data[$k]['buy_po_pack'][$k1]['container_time'] = $container['time'];
                                }else{
                                    $data[$k]['buy_po_pack'][$k1]['name'] = '';
                                    $data[$k]['buy_po_pack'][$k1]['container_status'] = '';
                                    $data[$k]['buy_po_pack'][$k1]['container_time'] = '';
                                }
                            }
                        }
                    }
                    
                }
            }
            // dump($data);die;

            return json_encode($data);
        }else{
            return view('list');
        }
        
    }


    function getContainerStatus($container_id)
    {
        $data=Db::name('container')->where(['id'=>$container_id])->select();
        if(!empty($data)){
            $data = $data[0];
            $lang=$this->lang;
            if ($data['arrival_day']>0){
                //完成
                $data['time'] = $data['arrival_day'];
                $data['status']='DISCHARGE';
            }elseif ($data['eta_day']>0 && !$data['arrival_day']){
                //到达
                $data['time'] = $data['eta_day'];
                $data['status']='ARRIVE';
            }elseif ($data['etd_day']>0 && !$data['eta_day'] && !$data['arrival_day']){
                //出发
                $data['time'] = $data['etd_day'];
                $data['status']='SALLING';
            }elseif ($data['ready_day']>0 && $data['sum_ctn']>0 && !$data['etd_day'] && !$data['eta_day'] && !$data['arrival_day']){
                //装柜
                $data['time'] = $data['ready_day'];
                $data['status']='LOADING';
            }elseif ($data['ready_day']>0 && $data['sum_ctn']==0 && !$data['etd_day'] && !$data['eta_day'] && !$data['arrival_day']){
                //准备
                $data['time'] = $data['ready_day'];
                $data['status']='READY';
            }
            //状态中的时间
            if($lang !='zh'){
                if($data['time']){
                    $data['status_time']=getTimeDate($data['arrival_day'],8);
                }
            }else{
                if($data['time']){
                    $data['status_time']=getTimeDate($data['arrival_day'],7);
                }
            }
            $returnData['name'] = $data['name'];
            $returnData['status'] = $data['status'];
            $returnData['time'] = isset($data['status_time']) ? $data['status_time'] : '';
        }else{
            $returnData = [];
        }

        return $returnData;
    }


    // 生成采购合同
    public function addBuyPo()
    {
        Db::startTrans();
        // try{
            // $this->getOrganizPoData($this->data);
            if(empty($this->data['paypoarr'])) return json_encode(array('status'=>2,'msg'=>lang("payment_arrangement_can't_be_empty")));
            if(empty($this->data['ids'])) return json_encode(array('status'=>2,'msg'=>lang("planned_order_can't_be_empty")));
            if(empty($this->data['terms'])) return json_encode(array('status'=>2,'msg'=>lang("contract_terms_can't_be_empty")));

            $noticeText = noticeText($this->data['data'],['bank_id'=>lang('bank_account'),'company_id'=>lang('designated_company'),'delivery_day'=>lang('delivery_time'),'port_id'=>lang('delivery_address'),'linkman_id'=>lang('contact')]);
            if(!empty($noticeText)) return json_encode($noticeText);

            unset($this->data['data']['country_id']);
            unset($this->data['data']['has_sum']);
            if(isset($this->data['data']['replace_sum'])){
                $this->data['data']['cost_sum'] = $this->data['data']['replace_sum'];
                unset($this->data['data']['replace_sum']);
            }
            $this->data['data']['delivery_day'] = strtotime($this->data['data']['delivery_day']);

            // $this->data['data']['cost_sum'] = $cost_sum;
            $this->data['data']['create_id'] = $this->user_id;
            $this->data['data']['create_at'] = time();
            $this->data['data']['status'] = 1;
            $po_id = insertData('buy_po',$this->data['data']);
            if(!$po_id) return json_encode(array('status'=>0,'msg'=>lang("purchase_contract_addition_failed")));
            // 给采购计划订单绑定采购合同ID
            foreach ($this->data['ids'] as $k => $v) {
                $res = updateData('buy_plan',['id'=>$v],['po_id'=>$po_id]);
            }
            if(!$res) return json_encode(array('status'=>0,'msg'=>lang("purchase_contract_addition_failed")));


            // 添加当前合同的其他费用,并获取其他费用合计
            if (isset($this->data['cost_list']) && !empty($this->data['cost_list'])) {
                $cost_sum = $this->insertPoCost($po_id,$this->data['cost_list']);
            }else{
                $cost_sum = 0;
            }


            // 添加合同关联的条款信息
            foreach ($this->data['terms'] as $k1 => $v1) {
                $res1 = insertData('buy_po_terms',['po_id'=>$po_id,'type'=>$k1,'content'=>$v1['content']]);
            }
            if(!$res1) return json_encode(array('status'=>0,'msg'=>lang("purchase_contract_addition_failed")));

            // 添加付款安排（付款百分比，和各个百分比时间）
            foreach ($this->data['paypoarr'] as $k2 => $v2) {
                $v2['po_id'] = $po_id;
                $v2['pay_day'] = strtotime($v2['pay_day']);
                $res2 = insertData('buy_po_pay',$v2);       
            }
            if(!$res2) return json_encode(array('status'=>0,'msg'=>lang("purchase_contract_addition_failed")));

            // 添加公司财务信息
            $fin_co_insert = [
                                'happen_day'=>$this->data['data']['delivery_day'],
                                'co_id'=>$this->data['data']['company_id'],
                                'type'=>1,
                                'amount'=>$this->data['data']['price_sum'] + $this->data['data']['paid_sum'],
                                'table_name'=>'buy_po',
                                'record_id'=>$po_id,
                                'create_id'=>$this->user_id,
                                'create_at'=>time(),
                            ];
            $res3 = insertData('fin_co',$fin_co_insert);

            if($po_id && $res){
                Db::commit();
                return json_encode(array('status'=>1,'msg'=>lang('purchase_contract_addition_successfully')));
            }else{
                Db::rollback();
                return json_encode(array('status'=>0,'msg'=>lang("purchase_contract_addition_failed")));
            }
        // }catch(\Exception $e){
        //     Db::rollback();
        //     return json_encode(array('status'=>500,'msg'=>lang('系统报错mysql')));
        // }
    }

    function getOrganizPoData($data)
    {

        $noticeText = noticeText($this->data['data'],['bank_id'=>lang('bank_account'),'company_id'=>lang('designated_company'),'delivery_day'=>lang('delivery_time'),'port_id'=>lang('delivery_address'),'linkman_id'=>lang('contact')]);
        if(!empty($noticeText)) return json_encode($noticeText);
        unset($this->data['data']['country_id']);
        unset($this->data['data']['has_sum']);
        if(isset($this->data['data']['replace_sum'])){
            $this->data['data']['cost_sum'] = $this->data['data']['replace_sum'];
            unset($this->data['data']['replace_sum']);
        }
        $this->data['data']['delivery_day'] = strtotime($this->data['data']['delivery_day']);
    }

    function insertPoCost($po_id,$cost_lst)
    {
        // 编辑合同其他费用
        $cost_sum = 0;
        foreach ($cost_lst as $k => $v) {
            $insertData['amount'] = $v['amount'];
            $insertData['apportion'] = $v['apportion'] == 'true' ? 1 :0;
            $insertData['is_replace_pay'] = $v['is_replace_pay'] == 'true' ? 1 :0;
            $insertData['remarks'] = $v['remarks'];
            $insertData['po_id'] = $po_id;
            $res = insertData('buy_po_cost',$insertData);
            if(!$res) return json_encode(array('status'=>0,'msg'=>lang('failed_to_add_other_purchase_contract_expenses')));
            // 代付前提下，计算合同代付合计
            if($insertData['is_replace_pay'] == 1) $cost_sum += $v['amount'];
        }
        return $cost_sum;
        
    }

    public function editBuyPo(Request $request)
    {   
        if(isset($this->data['request']) && $this->data['request'] == 'update'){

            if(!isset($this->data['po_id'])) return json_encode(array('status'=>2,'msg'=>lang("please_select_a_contract")));
            if(empty($this->data['paypoarr'])) return json_encode(array('status'=>2,'msg'=>lang("payment_arrangement_can't_be_empty")));
            if(empty($this->data['ids'])) return json_encode(array('status'=>2,'msg'=>lang("planned_order_can't_be_empty")));
            if(empty($this->data['terms'])) return json_encode(array('status'=>2,'msg'=>lang("contract_terms_can't_be_empty")));

            $noticeText = noticeText($this->data['data'],['bank_id'=>lang('bank_account'),'company_id'=>lang('designated_company'),'delivery_day'=>lang('delivery_time'),'port_id'=>lang('delivery_address'),'linkman_id'=>lang('contact')]);
            if(!empty($noticeText)) return json_encode($noticeText);

            unset($this->data['data']['country_id']);
            unset($this->data['data']['has_sum']);
            if(isset($this->data['data']['replace_sum'])){
                $this->data['data']['cost_sum'] = $this->data['data']['replace_sum'];
                unset($this->data['data']['replace_sum']);
            }
            $this->data['data']['delivery_day'] = strtotime($this->data['data']['delivery_day']);


            // 获取被修改的字段信息
            $updateInfo = model('Buy')->getupdatelogs($this->data);
            if($updateInfo){
                $buy_po_logs['happen_at'] = time();
                $buy_po_logs['po_id'] = $this->data['po_id'];
                $buy_po_logs['admin_id'] = $this->user_id;
                $buy_po_logs['content'] = $updateInfo;
                $buy_po_logs_insert = insertData('buy_po_logs',$buy_po_logs);
            }

            // $this->getOrganizPoData($this->data);

            // return $this->data;
            // 编辑合同其他费用，先删除之前有的，再新增
            if (isset($this->data['cost_list']) && !empty($this->data['cost_list'])) {
                $resDel = deleteData('buy_po_cost',['po_id'=>$this->data['po_id']]);
                $cost_sum = $this->insertPoCost($this->data['po_id'],$this->data['cost_list']);
            }else{
                $cost_sum = 0;
            }
            unset($this->data['data']['replace_sum']);
            $this->data['data']['cost_sum'] = $cost_sum;
            $res = updateData('buy_po',['id'=>$this->data['po_id']],$this->data['data']);
            if($res < 0) return json_encode(array('status'=>0,'msg'=>lang('edit_failed'))); 

            // 编辑合同的计划订单
            $res4 = updateData('buy_plan',['po_id'=>$this->data['po_id']],['po_id'=>0]);
            foreach ($this->data['ids'] as $k3 => $v3) {
                $res5 = updateData('buy_plan',['id'=>$v3],['po_id'=>$this->data['po_id']]);
            }

            // 删除当前po_id下的付款安排，然后新增付款安排
            $res1 = deleteData('buy_po_pay',['po_id'=>$this->data['po_id']]);
            // if(!$res1) return json_encode(array('status'=>500,'msg'=>lang('edit_failed'))); 
            // 添加付款安排（付款百分比，和各个百分比时间）
            foreach ($this->data['paypoarr'] as $k2 => $v2) {
                $v2['po_id'] = $this->data['po_id'];
                $v2['pay_day'] = strtotime($v2['pay_day']);
                $res2 = insertData('buy_po_pay',$v2);       
            }
            if(!$res2) return json_encode(array('status'=>0,'msg'=>lang('edit_failed')));

            // 编辑合同条款
            foreach ($this->data['terms'] as $k1 => $v1) {
                $res3 = updateData('buy_po_terms',['id'=>$v1['id']],['content'=>$v1['content']]);
            }
            if($res3<0) return json_encode(array('status'=>0,'msg'=>lang('edit_failed')));

            // 编辑装箱单信息
            if(isset($this->data['packing']) && !empty($this->data['packing'])){
                $res4 = model('Buy')->buyPoPack($this->data['packing'],$this->data['po_id']);
            }

            // 编辑同一公司采购合同信息
            $fin_co_insert = [
                                'happen_day'=>$this->data['data']['delivery_day'],
                                'co_id'=>$this->data['data']['company_id'],
                                'amount'=>$this->data['data']['price_sum'] + $this->data['data']['paid_sum'],
                                'update_id'=>$this->user_id,
                                'update_at'=>time(),
                            ];
            $res3 = updateData('fin_co',['record_id'=>$this->data['po_id']],$fin_co_insert);

            return json_encode(array('status'=>1,'msg'=>lang('edited_successfully')));
        }else{
            if($request->isAjax()){

            }else{
                // 根据合同ID  获取其计划订单（合同组成的订单）
                $plan_ids = getDatas('buy_plan',['id'],['po_id'=>$this->data['id']],'id desc');
                if(!empty($plan_ids)){
                    foreach ($plan_ids as $k => $v) {
                        $ids[] = $v['id'];
                    }
                    $idstr = implode(',', $ids);
                }else{
                    $idstr = '';
                }
                return view('buy/plan2po',['plan_ids'=>$idstr,'po_id'=>$this->data['id'],'title'=>lang("edit_purchase_contract"),'request'=>'edit']);
            }
        } 

    }

    public function submitEditPlan()
    {
        if($this->data['request'] == 'add'){

        }
    }


    // 批量签约
    public function batchSign()
    {
        if(!isset($this->data['buy_po_ids']) || empty($this->data['buy_po_ids'])) return json_encode(array('status'=>2,'msg'=>lang("please_select_contract_to_confirm_signature")));
        $res = model('Buy')->batchSet($this->data['buy_po_ids'],'sign');
        return json_encode($res);
    }

    // 批量收货
    public function batchReceipt()
    {
        if(!isset($this->data['buy_po_ids']) || empty($this->data['buy_po_ids'])) return json_encode(array('status'=>2,'msg'=>lang("select_contract_to_cofirm_receipt")));
        $res = model('Buy')->batchSet($this->data['buy_po_ids'],'receipt');
        return json_encode($res);
    }

    // 批量删除
    public function batchDel()
    {
        if(!isset($this->data['buy_po_ids']) || empty($this->data['buy_po_ids'])) return json_encode(array('status'=>2,'msg'=>lang("select_contract_to_delete")));
        $res = model('Buy')->batchSet($this->data['buy_po_ids'],'del',$this->user_id);
        return json_encode($res);
    }
}